<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
//        if ($e instanceof ModelNotFoundException) {
//            $e = new NotFoundHttpException($e->getMessage(), $e);
//        }
        // 如果请求来自 ajax, 则返回 json
        if ($request->ajax() || $request->wantsJson()) {
            $StatusCode = 200;
            // 非调试环境下，http状态码设置200，保证浏览器控制台不报错
//            if (!config('app.debug')) {
//                $StatusCode = 200;
//            }
            Log::info($e);
            $message = $e->getMessage();
            if ($e->getFile() && $e->getLine()) {
                $file = explode("/", $e->getFile());
                $message = $message . "(" . $file[count($file) - 1] . ": " . $e->getLine() . ")";
            }
            if ($e instanceof TokenMismatchException) {
                $message = "CSRF Token Mismatch";
            } else if ($e instanceof ValidationException) {
                return response()->json([
                    'status' => 422,
                    'msg' => '验证不通过',
                    'errors' => $e->validator->errors()
                ], $StatusCode);
            }
            return response()->json([
                'status' => 500,
                'msg' => $message,
            ], $StatusCode);
        }
        return parent::render($request, $e);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }
}
